package com.tocean.demo.service;

import com.alibaba.fastjson.JSONObject;
import com.tocean.demo.dto.ExaminationPaper;
import com.tocean.demo.dto.ExaminationSet;
import com.tocean.demo.dto.TagTreeNode;
import com.tocean.demo.entity.Attr.*;
import com.tocean.demo.entity.questionbank.ExamId;
import com.tocean.demo.entity.questionbank.Examination;
import com.tocean.demo.entity.questionbank.Question;
import com.tocean.demo.entity.questionbank.TestRelation;
import com.tocean.demo.repository.ExamIdRepository;
import com.tocean.demo.repository.ExaminationRepository;
import com.tocean.demo.repository.QuestBankRepository;
import com.tocean.demo.repository.TestRlationRepository;
import com.tocean.demo.util.SnowflakeIdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.text.SimpleDateFormat;
import java.util.*;


@Service
public class QuestBankService {

    @Autowired
    private QuestBankRepository quest_bankRepository;

    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;

    @Autowired
    WebService webService;

    @Autowired
    private TestRlationRepository testRlationRepository;

    @Autowired
    private ExaminationService examinationService;

    @Autowired
    private TestRelationService testRelationService;

    @Autowired
    private ExaminationRepository examinationRepository;

    @Autowired
    private ExamIdRepository examIdRepository;


    /**
     * 功能描述：保存一套试卷
     *
     */
    public void add(List<Question> quest_bank) {
        for(int i=0;i<quest_bank.size();i++){
            Question question = new Question();
            question  = quest_bankRepository.findById(quest_bank.get(i).getId()).get();
            if(question == null){
                quest_bankRepository.save(question);
            }
        }
    }

    /**
     * 根据试卷id返回试卷
     * @param tid
     * @return
     */
    public List<Question> select(Long tid){
        List<TestRelation> test = testRlationRepository.findAllByTestid(tid);

        List<Question> list = new ArrayList<>();

        for(int i =0;i<test.size();i++){
            Question quest = quest_bankRepository.findById(test.get(i).getQuestionid()).get();
            list.add(quest);
        }
        return list;
    }


    /**
     * 封装成试卷
     * 并添加试卷和题目id的联系
     * @param info
     * @param tid
     * @return
     */
    public List<Examination1> getExamination(List<Question> info, Long tid, String type){
        List<Examination1> exam = new ArrayList<>();
        for(int i =0;i<info.size();i++){
            TestRelation test = new TestRelation();
            test = testRlationRepository.findByTestidAndQuestionid(tid,info.get(i).getId());
            if(test == null) {
                test.setId(snowflakeIdWorker.nextId());
                test.setTestid(tid);
                test.setQuestionid(info.get(i).getId());
                testRlationRepository.save(test);
            }
            Examination1 ex;
            if(type.equals("练习")){
                //试卷id    题目id     题目内容    题目选项     题目标签
                ex = new Examination1(tid,info.get(i).getId(),info.get(i).getContent(),info.get(i).getAnswer(),info.get(i).getTag_name());//不添加截止日期和开始日期
            }
            else
                ex = new Examination1(tid,info.get(i).getId(),info.get(i).getContent(),info.get(i).getAnswer(),info.get(i).getTag_name());//添加截止日期和开始日期
            //还需要添加开始日期  截止日期
            exam.add(ex);
        }
        return exam;
    }

    /**
     * 向题库请求题目
     * @Auther:
     * @param tid
     * @param
     * @return
     */
        public List<Question> getUserInfoFromAuthority (String tid){

            String authorizeUrl = "http://120.79.248.126/api/questionPaper/get-questionPaper-by-id?examination=" +tid;//?examinationId=601062401827143680";
            Map<String, String> params = new HashMap<>();

            //发送Post数据并返回数据
            String data = webService.sendGetRequest(authorizeUrl,null);
            QuestionTrans list = JSONObject.parseObject(data, QuestionTrans.class);


            List<Question> question = new ArrayList<>();

            return question;
        }



    /**
     * 向题库对答案
     * @return 答案 map<id,answer>
     */
    public Boolean getTestAnswer (String tid,String content){
        String url = "http://120.79.248.126/api/answer/checkAnswer?" + "topicId=" + tid + "&contentList=" + content;

        String data = WebService.sendGetRequest(url,null);
        Boolean boo = JSONObject.parseObject(data,Boolean.class);
        return boo;
    }

    public String getAnswer(String id){
        String url = "http://120.79.248.126/api/answer/get-answer?" + "topicId=" + id;
        String data = WebService.sendGetRequest(url,null);
        String answer = JSONObject.parseObject(data,String.class);
        return answer;
    }

    /**
     * 根据id获取题目
     */
    public List<MyQuestion> findexam(String id){
        String url = "http://120.79.248.126/api/questionPaper/get-questionPaper-by-id?examinationId="+id;
        String data = WebService.sendGetRequest(url,null);
        QuestionTrans questionTrans = JSONObject.parseObject(data,QuestionTrans.class);
        List<MyQuestion> myQuestions = new ArrayList<>();

        for(int i=0;i<questionTrans.getQuestions().size();i++) {
            String index = questionTrans.getQuestions().get(i).getIndex().trim();
            String idd = questionTrans.getQuestions().get(i).getTopic().getId().trim();//题目id
            String content = questionTrans.getQuestions().get(i).getTopic().getContent().trim();
            String tags = questionTrans.getQuestions().get(i).getTags().trim();
            String tag = examinationService.setTag(tags);
            StringBuilder answer1 = new StringBuilder();
            List<String> str = new ArrayList<>();
            for (int j = 0; j < questionTrans.getQuestions().get(i).getOptions().size(); j++) {
                answer1.append(questionTrans.getQuestions().get(i).getOptions().get(j).getContent().trim() + "|");
                str.add(questionTrans.getQuestions().get(i).getOptions().get(j).getContent().trim());
            }
            String answer = answer1.toString().trim();
            MyQuestion questions = new MyQuestion(id,idd,index,content,str,tag);
            myQuestions.add(questions);
            addExam(idd,index,content,answer,tag);
            testRelationService.addRelation(id,idd);
        }
        return myQuestions;
    }


    /**
     * 向数据库存入考试试卷
     * @param id
     * @param index
     * @param content
     * @param answer
     * @param tags
     */
    @Transactional
    public void addExam(String id,String index,String content,String answer,String tags){
        Question question = new Question();
//        question  = quest_bankRepository.findById(Long.valueOf(id)).get();
        if(!quest_bankRepository.findById(Long.valueOf(id)).isPresent()) {
            question.setId(Long.valueOf(id));
            question.setIndexs(Integer.valueOf(index));
            question.setContent(content);
            question.setAnswer(answer);
            question.setTag_name(tags);
            quest_bankRepository.save(question);
        };
    }

    /**
     * 获取所有标签，只选出单选题  远程url
     */
    public List<MyQuestion>  getAllTags(String tags){
        String url = "http://120.79.248.126/api/tag/get-all-tags";
        String data = WebService.sendGetRequest(url,null);
        List<TagTreeNode> tagTreeNodes = JSONObject.parseArray(data,TagTreeNode.class);
        List<String> list = new ArrayList<>();
        String grade = tags.substring(0,3).trim();
        String subject = tags.substring(3).trim();
        for(int i=0;i<tagTreeNodes.size();i++){
            if(tagTreeNodes.get(i).getTagValue().equalsIgnoreCase("年级")){
                for(int j=0;j<tagTreeNodes.get(i).getChildren().size();j++){
                    if(tagTreeNodes.get(i).getChildren().get(j).getTagValue().equalsIgnoreCase(grade))
                    {
                        list.add(tagTreeNodes.get(i).getChildren().get(j).getTagId());
                    }
                }
            }
        }

        for(int i=0;i<tagTreeNodes.size();i++){
            if(tagTreeNodes.get(i).getTagValue().equalsIgnoreCase("科目")){
                for(int j=0;j<tagTreeNodes.get(i).getChildren().size();j++){
                    if(tagTreeNodes.get(i).getChildren().get(j).getTagValue().equalsIgnoreCase(subject))
                    {
                        list.add(tagTreeNodes.get(i).getChildren().get(j).getTagId());
                    }
                }
            }
        }

        for(int i=0;i<tagTreeNodes.size();i++){
            if(tagTreeNodes.get(i).getTagValue().equalsIgnoreCase("题型")){
                for(int m=0;m<tagTreeNodes.get(i).getChildren().size();m++){
                    if(tagTreeNodes.get(i).getChildren().get(m).getTagValue().equalsIgnoreCase("单选题"))
                    {
                        list.add(tagTreeNodes.get(i).getChildren().get(m).getTagId());
                    }
                }
            }
        }
        return getQuestionPaperByTag(list);
    }


    /**
     * 根据标签返回试卷   远程URL
     */
    public List<MyQuestion> getQuestionPaperByTag(List<String> str){
        String url = "http://120.79.248.126/api/questionPaper/get-questionPaper-by-tag?tagIdList="+ str.get(0) + "&tagIdList=" + str.get(1) + "&tagIdList=" + str.get(2);
        String data = WebService.sendGetRequest(url,null);
        List<ExaminationPaper> examinationPapers = JSONObject.parseArray(data,ExaminationPaper.class);
        List<MyQuestion> myQuestions = new ArrayList<>();
        for(int i=0;i<examinationPapers.size();i++) {
            myQuestions = findexam(examinationPapers.get(i).getId());
            examinationService.AddExam(myQuestions);
        }
//        myQuestions = findexam(examinationPapers.get(0).getId());
//        examinationService.AddExam(myQuestions);
        return myQuestions;
    }


    /**
     * 获取本地数据库所有题目
     * @return
     */
    public List<ExaminationSet> getAllExamPaper(String type){
        List<ExamId> list = examIdRepository.findAll();
        List<Examination> examinations = new ArrayList<>();
        List<ExaminationSet> examinationSet = new ArrayList<>();
        for(int i=0;i<list.size();i++){
            examinations = examinationRepository.findAllByTid(list.get(i).getId());
            List<MyQuestion> myQuestions = new ArrayList<>();
            for(int m=0;m<examinations.size();m++) {
                String[] str = examinations.get(m).getAnswer().split("\\|");
                List<String> strings = new ArrayList<>();
                for(int s=0;s<str.length;s++)
                    strings.add(str[s]);
                MyQuestion questions = new MyQuestion(examinations.get(m).getTid(), examinations.get(m).getCid(), examinations.get(m).getIndexs(), examinations.get(m).getContent(), strings, examinations.get(m).getTag_Name());
                myQuestions.add(questions);
            }
            ExaminationSet examsets = new ExaminationSet();
            List<MyQuestion> quest = sortById(myQuestions);
            examsets.setMyQuestions(quest);
            examsets.setType(type);
            examinationSet.add(examsets);
        }

        return examinationSet;
    }

    /**
     * 排序
     */
    public List<MyQuestion> sortById(List<MyQuestion> quest){
        List<MyQuestion> ret = new ArrayList<>();
        for(int i=0;i<quest.size();i++){
            for(int j=0;j<quest.size();j++){
                int ss = i+1;
                if(quest.get(j).getIndexs().equals(String.valueOf(ss))){
                    ret.add(quest.get(j));
                    break;
                }
            }
        }
        return ret;
    }

    /**
     * 根据标签返回自己的数据库试卷
     */
    public List<ExaminationSet> getAllExamByTags(String tagname,String type){
        List<ExamId> examId =  examIdRepository.findAll();
        List<ExaminationSet> examinationSets = new ArrayList<>();
        for(int i=0;i<examId.size();i++){
            List<Examination> examinations = examinationRepository.findAllByTid(examId.get(i).getId());
            if(examinations.get(0).getTag_Name().equals(tagname)){
                List<MyQuestion> myQuestions = new ArrayList<>();
                for(int m=0;m<examinations.size();m++) {
                    String[] str = examinations.get(m).getAnswer().split("\\|");
                    List<String> strings = new ArrayList<>();
                    for(int s=0;s<str.length;s++)
                        strings.add(str[s]);
                    MyQuestion questions = new MyQuestion(examinations.get(m).getTid(), examinations.get(m).getCid(), examinations.get(m).getIndexs(), examinations.get(m).getContent(), strings, examinations.get(m).getTag_Name());
                    myQuestions.add(questions);
                }
                ExaminationSet examsets = new ExaminationSet();
                List<MyQuestion> quest = sortById(myQuestions);
                examsets.setMyQuestions(quest);
                examsets.setType(type);
                examinationSets.add(examsets);
            }
        }
        return examinationSets;
    }


    public void setTime(ExaminationSet examinationSet){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);

        String startTime = format.format(cal.getTime());
        String mid = startTime.substring(0,startTime.length() - 2);
        startTime = mid + "00";
        try {
            date = format.parse(startTime);//获取开始时间
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        cal.add(Calendar.HOUR , 2);// 24小时制

        Date endTime  = cal.getTime();
        String end = format.format(endTime);

        String mid1 = end.substring(0,end.length() - 2);
        end = mid1 + "00";
        try {
            endTime = format.parse(end);//获取截止时间
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        examinationSet.setStartTime(date);
        examinationSet.setEndTime(endTime);
        examinationSet.setCountTime(7200);
    }
}
